using Microsoft.Extensions.Logging;
using System.Text.Json;
using AgentFrameworkDemo.Models;
using Microsoft.Extensions.DependencyInjection;

namespace AgentFrameworkDemo.Services;

/// <summary>
/// Agent函数工具 - Microsoft风格的Agent转工具实现
/// 提供简洁的API将Agent转换为可调用的AI函数
/// </summary>
public static class AgentFunctionTool
{
    private static IServiceProvider? _serviceProvider;
    private static readonly Dictionary<string, AIFunction> _functions = new();
    private static readonly object _lock = new object();

    /// <summary>
    /// 初始化AgentFunctionTool（应用启动时调用）
    /// </summary>
    public static void Initialize(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));

        // 注册企业级服务
        var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
        var auditLogger = loggerFactory.CreateLogger("AgentFunctionTool.Audit");

        auditLogger.LogInformation("AgentFunctionTool initialized with enterprise support");
    }

    /// <summary>
    /// 将Agent转换为AI函数 - Microsoft标准方式
    /// </summary>
    /// <param name="agent">要转换的Agent</param>
    /// <param name="name">函数名称（可选，默认使用Agent名称）</param>
    /// <param name="description">函数描述（可选，默认使用Agent描述）</param>
    /// <param name="parameterSchema">自定义参数模式（可选）</param>
    /// <returns>AI函数</returns>
    public static AIFunction AsAIFunction(
        this Agent agent,
        string? name = null,
        string? description = null,
        object? parameterSchema = null)
    {
        if (_serviceProvider == null)
            throw new InvalidOperationException("AgentFunctionTool未初始化，请先调用Initialize()");

        var functionName = name ?? agent.Definition.Name;
        var functionDescription = description ?? agent.Definition.Description;
        var schema = parameterSchema ?? CreateDefaultParameterSchema();

        var loggerFactory = _serviceProvider.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("AgentFunctionTool");
        var agentManager = _serviceProvider.GetRequiredService<IAgentManager>();

        var function = new AIFunction
        {
            Name = functionName,
            Description = functionDescription,
            Parameters = schema,
            Execute = async (parameters) => await ExecuteAgentWithEnterpriseSupportAsync(
                agent, parameters, loggerFactory, agentManager)
        };

        // 缓存函数以便管理
        lock (_lock)
        {
            _functions[functionName] = function;
        }

        logger.LogDebug("Agent转换为AI函数: {AgentId} -> {FunctionName}", agent.Id, functionName);

        return function;
    }

    /// <summary>
    /// 批量转换Agent为AI函数
    /// </summary>
    public static List<AIFunction> AsAIFunctions(this IEnumerable<Agent> agents)
    {
        return agents.Select(agent => agent.AsAIFunction()).ToList();
    }

    /// <summary>
    /// 直接执行Agent（无需转换为函数）
    /// </summary>
    public static async Task<object> ExecuteAsync(
        this Agent agent,
        string input,
        Dictionary<string, object>? context = null,
        ExecutionOptions? options = null)
    {
        if (_serviceProvider == null)
            throw new InvalidOperationException("AgentFunctionTool未初始化");

        var loggerFactory = _serviceProvider.GetRequiredService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("AgentFunctionTool");
        var agentManager = _serviceProvider.GetRequiredService<IAgentManager>();

        var parameters = new Dictionary<string, object> { ["input"] = input };
        if (context != null)
        {
            parameters["context"] = context;
        }

        return await ExecuteAgentWithEnterpriseSupportAsync(agent, parameters, loggerFactory, agentManager, options);
    }

    /// <summary>
    /// 查找已注册的函数
    /// </summary>
    public static AIFunction? FindFunction(string name)
    {
        lock (_lock)
        {
            return _functions.TryGetValue(name, out var func) ? func : null;
        }
    }

    /// <summary>
    /// 获取所有已注册的函数
    /// </summary>
    public static IReadOnlyDictionary<string, AIFunction> GetAllFunctions()
    {
        lock (_lock)
        {
            return _functions.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
        }
    }

    /// <summary>
    /// 清除所有缓存的函数
    /// </summary>
    public static void ClearCache()
    {
        lock (_lock)
        {
            _functions.Clear();
        }
    }

    /// <summary>
    /// 创建默认参数模式
    /// </summary>
    private static object CreateDefaultParameterSchema()
    {
        return new
        {
            type = "object",
            properties = new
            {
                input = new
                {
                    type = "string",
                    description = "传递给Agent的输入文本或指令"
                },
                context = new
                {
                    type = "object",
                    description = "可选的上下文信息"
                }
            },
            required = new[] { "input" },
            additionalProperties = true
        };
    }

    /// <summary>
    /// 执行Agent的核心逻辑（包含企业级支持）
    /// </summary>
    private static async Task<object> ExecuteAgentWithEnterpriseSupportAsync(
        Agent agent,
        Dictionary<string, object> parameters,
        ILoggerFactory loggerFactory,
        IAgentManager agentManager,
        ExecutionOptions? options = null)
    {
        var startTime = DateTime.UtcNow;
        var executionId = Guid.NewGuid().ToString();
        var logger = loggerFactory.CreateLogger("AgentFunctionTool");
        var auditLogger = loggerFactory.CreateLogger("AgentFunctionTool.Audit");

        try
        {
            // 企业级：执行前检查
            await PreExecutionChecksAsync(agent, parameters, auditLogger, executionId);

            // 构建Agent请求
            var input = parameters.GetValueOrDefault("input", "")?.ToString() ?? "";
            var context = parameters.GetValueOrDefault("context") as Dictionary<string, object> ?? new Dictionary<string, object>();

            var agentRequest = new AgentRequest
            {
                AgentId = agent.Id,
                Input = input,
                SessionId = $"agent-function-{executionId}",
                Context = new Dictionary<string, object>(context)
                {
                    ["calledAsAIFunction"] = true,
                    ["functionParameters"] = parameters,
                    ["executionId"] = executionId,
                    ["startTime"] = startTime,
                    ["enterpriseMode"] = true
                },
                Options = options ?? new ExecutionOptions
                {
                    TimeoutSeconds = 120,
                    EnableStreaming = false,
                    IncludeToolCalls = agent.Definition.Capabilities.EnableTools
                }
            };

            // 执行Agent
            var response = await agentManager.ExecuteAsync(agentRequest);

            // 企业级：执行后处理
            await PostExecutionProcessingAsync(response, auditLogger, executionId);

            // Microsoft风格的响应格式
            var result = new
            {
                success = response.Success,
                content = response.Content,
                execution_id = executionId,
                agent_id = agent.Id,
                agent_name = agent.Definition.Name,
                execution_time = DateTime.UtcNow - startTime,
                metadata = response.Metadata as Dictionary<string, object> ?? new Dictionary<string, object>(),
                error = response.Success ? null : response.ErrorMessage,
                // 企业级元数据
                enterprise = new
                {
                    audit_log_id = executionId,
                    performance_metrics = new
                    {
                        total_execution_time_ms = (DateTime.UtcNow - startTime).TotalMilliseconds,
                        agent_execution_time_ms = response.ExecutionTime.TotalMilliseconds
                    },
                    security_info = new
                    {
                        caller_context = context.GetValueOrDefault("caller_info"),
                        permissions_checked = true,
                        audit_trail_enabled = true
                    }
                }
            };

            if (response.Success)
            {
                logger.LogInformation("Agent执行成功: {AgentId}, 执行ID: {ExecutionId}, 耗时: {ElapsedMs}ms",
                    agent.Id, executionId, (DateTime.UtcNow - startTime).TotalMilliseconds);
            }
            else
            {
                logger.LogWarning("Agent执行失败: {AgentId}, 执行ID: {ExecutionId}, 错误: {Error}",
                    agent.Id, executionId, response.ErrorMessage);
            }

            return result;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Agent执行异常: {AgentId}, 执行ID: {ExecutionId}", agent.Id, executionId);

            // 企业级：异常审计
            await LogExceptionAsync(ex, agent, parameters, auditLogger, executionId);

            return new
            {
                success = false,
                error = ex.Message,
                execution_id = executionId,
                agent_id = agent.Id,
                agent_name = agent.Definition.Name,
                execution_time = DateTime.UtcNow - startTime,
                exception_type = ex.GetType().Name,
                // 企业级异常信息
                enterprise = new
                {
                    audit_log_id = executionId,
                    error_details = new
                    {
                        exception_type = ex.GetType().Name,
                        stack_trace = ex.StackTrace,
                        inner_exception = ex.InnerException?.Message
                    },
                    support_info = new
                    {
                        troubleshooting_id = Guid.NewGuid().ToString(),
                        error_category = CategorizeError(ex),
                        suggested_action = GetSuggestedAction(ex)
                    }
                }
            };
        }
    }

    /// <summary>
    /// 企业级：执行前检查
    /// </summary>
    private static async Task PreExecutionChecksAsync(
        Agent agent,
        Dictionary<string, object> parameters,
        ILogger auditLogger,
        string executionId)
    {
        // 权限检查
        await CheckPermissionsAsync(agent, parameters, auditLogger, executionId);

        // 资源检查
        await CheckResourcesAsync(agent, auditLogger, executionId);

        // 安全检查
        await CheckSecurityAsync(parameters, auditLogger, executionId);

        auditLogger.LogInformation("执行前检查完成: {ExecutionId}", executionId);
    }

    /// <summary>
    /// 企业级：执行后处理
    /// </summary>
    private static async Task PostExecutionProcessingAsync(
        AgentResponse response,
        ILogger auditLogger,
        string executionId)
    {
        // 更新执行统计
        await UpdateExecutionStatisticsAsync(response, auditLogger, executionId);

        // 记录性能指标
        await LogPerformanceMetricsAsync(response, auditLogger, executionId);

        // 检查异常模式
        await CheckForAnomalousPatternsAsync(response, auditLogger, executionId);

        auditLogger.LogInformation("执行后处理完成: {ExecutionId}", executionId);
    }

    /// <summary>
    /// 企业级：权限检查
    /// </summary>
    private static async Task CheckPermissionsAsync(
        Agent agent,
        Dictionary<string, object> parameters,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            // 模拟权限检查逻辑
            var hasPermission = true; // 实际中会检查调用者权限

            auditLogger.LogDebug("权限检查: {AgentId}, 权限: {HasPermission}, 执行ID: {ExecutionId}",
                agent.Id, hasPermission, executionId);
        });
    }

    /// <summary>
    /// 企业级：资源检查
    /// </summary>
    private static async Task CheckResourcesAsync(
        Agent agent,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            // 模拟资源检查逻辑
            var hasResources = true; // 实际中会检查系统资源

            auditLogger.LogDebug("资源检查: {AgentId}, 资源充足: {HasResources}, 执行ID: {ExecutionId}",
                agent.Id, hasResources, executionId);
        });
    }

    /// <summary>
    /// 企业级：安全检查
    /// </summary>
    private static async Task CheckSecurityAsync(
        Dictionary<string, object> parameters,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            // 模拟安全检查逻辑
            var isSecure = true; // 实际中会检查输入安全性

            auditLogger.LogDebug("安全检查: 参数数量: {ParamCount}, 安全: {IsSecure}, 执行ID: {ExecutionId}",
                parameters.Count, isSecure, executionId);
        });
    }

    /// <summary>
    /// 企业级：更新执行统计
    /// </summary>
    private static async Task UpdateExecutionStatisticsAsync(
        AgentResponse response,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            // 模拟统计更新逻辑
            auditLogger.LogDebug("更新执行统计: 成功: {Success}, 耗时: {ElapsedMs}ms, 执行ID: {ExecutionId}",
                response.Success, response.ExecutionTime.TotalMilliseconds, executionId);
        });
    }

    /// <summary>
    /// 企业级：记录性能指标
    /// </summary>
    private static async Task LogPerformanceMetricsAsync(
        AgentResponse response,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            // 模拟性能指标记录
            auditLogger.LogDebug("记录性能指标: 执行ID: {ExecutionId}, 性能数据已记录", executionId);
        });
    }

    /// <summary>
    /// 企业级：检查异常模式
    /// </summary>
    private static async Task CheckForAnomalousPatternsAsync(
        AgentResponse response,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            // 模拟异常模式检查
            auditLogger.LogDebug("异常模式检查: 执行ID: {ExecutionId}, 检查完成", executionId);
        });
    }

    /// <summary>
    /// 企业级：记录异常
    /// </summary>
    private static async Task LogExceptionAsync(
        Exception ex,
        Agent agent,
        Dictionary<string, object> parameters,
        ILogger auditLogger,
        string executionId)
    {
        await Task.Run(() =>
        {
            auditLogger.LogError(ex, "Agent执行异常审计: {AgentId}, 执行ID: {ExecutionId}, 参数: {@Parameters}",
                agent.Id, executionId, parameters);
        });
    }

    /// <summary>
    /// 企业级：错误分类
    /// </summary>
    private static string CategorizeError(Exception ex)
    {
        return ex switch
        {
            TimeoutException => "TIMEOUT",
            UnauthorizedAccessException => "PERMISSION",
            ArgumentException => "INVALID_INPUT",
            InvalidOperationException => "OPERATION_ERROR",
            _ => "SYSTEM_ERROR"
        };
    }

    /// <summary>
    /// 企业级：获取建议操作
    /// </summary>
    private static string GetSuggestedAction(Exception ex)
    {
        return ex switch
        {
            TimeoutException => "请重试或增加超时时间",
            UnauthorizedAccessException => "请检查权限设置",
            ArgumentException => "请检查输入参数格式",
            InvalidOperationException => "请检查Agent状态",
            _ => "请联系系统管理员"
        };
    }
}

/// <summary>
/// Microsoft风格的AI函数定义
/// </summary>
public class AIFunction
{
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public object Parameters { get; set; } = new object();
    public Func<Dictionary<string, object>, Task<object>> Execute { get; set; } = async _ => new object();

    /// <summary>
    /// 使用参数字典执行函数
    /// </summary>
    public async Task<object> InvokeAsync(Dictionary<string, object> parameters)
    {
        return await Execute(parameters);
    }

    /// <summary>
    /// 使用JSON字符串参数执行函数
    /// </summary>
    public async Task<object> InvokeAsync(string jsonParameters)
    {
        try
        {
            var parameters = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonParameters)
                           ?? new Dictionary<string, object>();
            return await InvokeAsync(parameters);
        }
        catch (JsonException ex)
        {
            throw new ArgumentException($"无效的JSON参数: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 使用简单字符串输入执行函数（自动包装为input参数）
    /// </summary>
    public async Task<object> InvokeWithStringInputAsync(string input)
    {
        var parameters = new Dictionary<string, object> { ["input"] = input };
        return await InvokeAsync(parameters);
    }

    /// <summary>
    /// 异步执行函数（带超时控制）
    /// </summary>
    public async Task<object> InvokeAsync(Dictionary<string, object> parameters, TimeSpan timeout)
    {
        using var cts = new CancellationTokenSource(timeout);
        try
        {
            return await Execute(parameters).WaitAsync(cts.Token);
        }
        catch (OperationCanceledException)
        {
            throw new TimeoutException($"函数执行超时: {timeout.TotalSeconds}秒");
        }
    }

    /// <summary>
    /// 转换为字符串表示
    /// </summary>
    public override string ToString()
    {
        return $"AIFunction(Name: {Name}, Description: {Description})";
    }
}